<template>
  <div id="app">
    <el-container>
      <el-header>
        <site-header />
      </el-header>
      <!-- 添加全局调试选项 -->
      <div v-if="showDebugOptions" class="debug-container">
        <el-button size="small" @click="clearLoginState" type="danger">清除登录状态</el-button>
        <el-button size="small" @click="showDebugOptions = false">隐藏</el-button>
      </div>
      <el-main>
        <router-view />
      </el-main>
      <el-footer>
        <site-footer />
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import SiteHeader from '@/components/layout/SiteHeader.vue'
import SiteFooter from '@/components/layout/SiteFooter.vue'

export default {
  name: 'App',
  components: {
    SiteHeader,
    SiteFooter
  },
  data() {
    return {
      showDebugOptions: false,
      refreshInterval: null
    }
  },
  computed: {
    ...mapGetters({
      error: 'error',
      isAuthenticated: 'auth/isAuthenticated'
    })
  },
  methods: {
    ...mapActions({
      clearError: 'clearError',
      refreshAuthState: 'auth/refreshAuthState',
      logoutAction: 'auth/logout'
    }),
    
    // 添加清除登录状态的方法
    clearLoginState(shouldRefresh = true) {
      // 清除sessionStorage中的token和user
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('user');
      
      // 执行登出操作
      this.logoutAction();
      
      // 刷新页面
      if (shouldRefresh) {
        this.$router.go(0);
        // 提示用户
        this.$message.success('登录状态已清除，页面将刷新');
      }
    },
    
    // 设置ResizeObserver错误处理器
    setupResizeObserverErrorHandler() {
      // 方法1: 使用事件监听器抑制错误
      window.addEventListener('error', (event) => {
        if (
          event && 
          event.message && 
          typeof event.message === 'string' && 
          event.message.includes('ResizeObserver loop')
        ) {
          event.stopImmediatePropagation();
          event.preventDefault();
          return false;
        }
      }, true);
      
      // 方法2: 使用全局错误处理函数
      const originalOnError = window.onerror;
      window.onerror = function(message, source, lineno, colno, error) {
        if (message && typeof message === 'string' && message.includes('ResizeObserver loop')) {
          return true; // 阻止错误传播
        }
        return originalOnError ? originalOnError(message, source, lineno, colno, error) : false;
      };
      
      // 方法3: 定义自定义ResizeObserver以防止循环
      try {
        if (typeof window.ResizeObserver !== 'undefined') {
          const originalResizeObserver = window.ResizeObserver;
          window.ResizeObserver = class CustomResizeObserver extends originalResizeObserver {
            constructor(callback) {
              const safeCallback = (entries, observer) => {
                try {
                  callback(entries, observer);
                } catch (e) {
                  if (e && e.message && typeof e.message === 'string' && e.message.includes('ResizeObserver loop')) {
                    console.warn('已抑制 ResizeObserver 循环错误');
                    return;
                  }
                  throw e;
                }
              };
              super(safeCallback);
            }
          };
        }
      } catch (error) {
        console.error('设置 ResizeObserver 错误处理器失败');
      }
      
      // 方法4: 直接抑制控制台错误
      const originalConsoleError = console.error;
      console.error = function(...args) {
        if (args && args.length > 0 && typeof args[0] === 'string' && args[0].includes('ResizeObserver loop')) {
          return; // 不显示ResizeObserver循环错误
        }
        originalConsoleError.apply(console, args);
      };
    },
    
    // 添加检测特殊键组合方法
    checkDebugKeyCombo(event) {
      // 检测 Ctrl+Shift+D 组合键
      if (event.ctrlKey && event.shiftKey && event.key === 'D') {
        this.showDebugOptions = !this.showDebugOptions;
      }
    }
  },
  watch: {
    // 监听错误状态，当出现分类数据错误时立即清除
    error(newVal) {
      if (newVal && typeof newVal === 'string' && newVal.includes('分类数据')) {
        this.clearError();
      }
    }
  },
  created() {
    // 设置ResizeObserver错误处理
    this.setupResizeObserverErrorHandler();
    
    // 添加键盘事件监听器
    window.addEventListener('keydown', this.checkDebugKeyCombo);
  },
  mounted() {
    // 定期刷新认证状态 - 仅在用户已登录时
    this.refreshInterval = setInterval(() => {
      if (this.isAuthenticated) {
        this.refreshAuthState();
      }
    }, 300000); // 每5分钟刷新一次
  },
  beforeUnmount() {
    // 组件卸载前清除定时器和事件监听器
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
    
    window.removeEventListener('keydown', this.checkDebugKeyCombo);
  }
}
</script>

<style lang="scss">
@use "sass:color";

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  min-height: 100vh;
}

.el-header {
  padding: 0;
}

.el-main {
  padding: 20px;
  min-height: calc(100vh - 160px);
}

.el-footer {
  padding: 20px;
}

.debug-container {
  position: fixed;
  top: 70px;
  right: 10px;
  z-index: 9999;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 10px;
}

// 修复Element Plus图片预览器
.el-image-viewer__wrapper {
  position: fixed !important;
  top: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  left: 0 !important;
  z-index: 9999 !important;
}

.el-image-viewer__mask {
  position: absolute !important;
  width: 100% !important;
  height: 100% !important;
  top: 0 !important;
  left: 0 !important;
  opacity: 0.5 !important;
  background: #000 !important;
}

// 增加预览图片的尺寸
.el-image-viewer__img {
  max-width: 80% !important;
  max-height: 80% !important;
}
</style> 